nice_things/io/FileDescriptor.sh
FileDescriptor is a "singleton" pseudo-class. There is only one instance of global state.
File descriptors are an extremely scarce resource in POSIX sh. There are only 10 of them, and 3 are already in use by stdin, stdout and stderr, leaving only 7 available for program use. If a shared library uses an FD by number, it is prone to collisions with other libraries using FDs. The open and close functions solve this issue by picking FDs from a list and keeping an internal global state of FDs in use. As long as libraries and application code use these functions to allocate and release FDs, no collisions will happen. These functions make 7 FDs available, starting from number 9 down to number 3.
Usage examples
output_file=/path/to/file.out
# Open FD for writing, with complete error handling
open output_fd "$output_file" w || {
case $? in
24) abort "Failed to open file at '${output_file}': No FD available, resource exhausted." ;;
25) abort "Failed to open file at '${output_file}' for writing: File exists." ;;
*) abort "Unknown error while trying to open file at '${output_file}'" ;;
esac
}
# Write to FD
printf 'Some data\n' >&"$output_fd"
# Close FD
close "$output_fd"
close
Since 0.3.0 · Source
import "{ close }" from nice_things/io/FileDescriptor_close.sh
Synopsisclose <fd>
Configuration
–
Description
Close the file descriptor with number <fd>.
Options
–
Operands<fd>: The number of a file description retrieved with the open function.
Stdin
–
Stdout
–
Stderr
–
Exit status
0: Successful completion.11: Invalid or missing arguments (abort).123: Unexpected error (abort).
Abort
- Aborts on invalid or missing arguments.
- Aborts on unexpected error.
Usage examples
close "$file_fd"
open
Since 0.3.0 · Source
import "{ open }" from nice_things/io/FileDescriptor_open.sh
Synopsisopen <out_var> <file> [<mode>]
Configuration
–
Description
Open a file descriptor and assign its number to <out_var>.
If <file> is a number between 0 and 9, the same file opened in the FD identified by that number will be opened.
By default, <file> is opened read-only. An optional <mode> parameter can be used to select a different mode:
w: Write – uses the>redirection operator.fw: Force-write – uses the>|redirection operator.rw: Read-write – uses the<>redirection operator.
Options
–
Operands
<out_var>: Output variable; the FD number will be written to this variable.<file>: The file to open; if a number between 0-9, will open the same file as that FD.<mode>: Optional mode, read-only by default; May bew(write),fw(force-write),rw(read-write).
Stdin
–
Stdout
–
Stderr
–
Exit status
0: Successful completion.11: Invalid or missing arguments (abort).24: No FD available, resource exhausted.25: File exists (when<mode>isw).123: Unexpected error (abort).
Abort
- Aborts on invalid or missing arguments.
- Aborts on unexpected error.
Usage examples
open file_fd "$file"